package com.vq.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vq.entity.Community;
import com.vq.entity.CommunityMember;
import com.vq.entity.User;
import com.vq.mapper.CommunityMemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommunityMemberService {
    @Autowired
    CommunityMemberMapper communityMemberMapper;

    @Autowired
    UserService userService;
    @Autowired
    CommunityService communityService;

    public boolean insert(String account, Long communityId) {
        //确保该用户真实存在
        User user = userService.selectByAccount(account, false);
        if (user==null) return false;
        //确保该社区真实存在且该用户不是该社区的创建人
        Community community = communityService.selectById(communityId);
        if (community==null) return false;
        if (community.getAccount().equals(account)) return false;
        //查询该用户是否已经加入该社区
        LambdaQueryWrapper<CommunityMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CommunityMember::getAccount,account).eq(CommunityMember::getCommunityId, communityId);
        CommunityMember communityMember = communityMemberMapper.selectOne(lqw);
        if (communityMember!=null) return false;
        //加入社区
        communityMemberMapper.insert(new CommunityMember(account, communityId));
        return communityService.addCommunity(communityId);
    }

    public boolean deleteByCommunityId(String account, Long communityId) {
        LambdaQueryWrapper<CommunityMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CommunityMember::getAccount, account).eq(CommunityMember::getCommunityId, communityId);
        boolean bo = communityMemberMapper.delete(lqw)==1;
        bo = bo && communityService.quitCommunity(communityId);
        return bo;
    }

    public List<CommunityMember> selectByAccount(String account) {
        LambdaQueryWrapper<CommunityMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CommunityMember::getAccount, account);
        return communityMemberMapper.selectList(lqw);
    }
}
